import {listProjects, addProjects, updateProjects, updateSequence, removeProjects} from '_api/projects/projects'
import {_Promise} from "_libs/util";
import Vue from "vue";

export default {
  namespaced: true,
  state: {
    projectsList: []
  },
  mutations: {
    setProjectsList(state, projectsList) {
      state.projectsList = projectsList.filter(func => {
        if (func.typeEntity != undefined){
          func.typeName = func.typeEntity.name
        }
        return func;
      })
    },
    addProjects(state, projects) {
      state.projectsList.unshift(projects);
    },
    updateProjects(state, projects) {
      for (let i = 0; i < state.projectsList.length; i++) {
        let existsProjects = state.projectsList[i];
        if (existsProjects.id === projects.id) {
          let keys = Object.keys(projects);
          keys.forEach(key => {
            Vue.set(state.projectsList[i], key, projects[key])
          })
          break
        }
      }
    },
    removeProjects(state, projects) {
      state.projectsList = state.projectsList.filter(existsProjects => {
        if (existsProjects.id !== projects.id) {
          return existsProjects;
        }
      })
    }
  },
  actions: {
    // 获取所有项目类型
    listProjects({state, commit}) {
      return _Promise(listProjects(), res => {
        commit('setProjectsList', res.data)
      })
    },

    // 添加项目类型
    addProjects({state, commit}, projects) {
      return _Promise(addProjects(projects), res => {
        commit('addProjects', res.data)
      })
    },

    // 更新项目类型
    updateProjects({state, commit}, projects) {
      return _Promise(updateProjects(projects), res => {
        commit('updateProjects', res.data)
      })
    },

    // 更新新闻
    updateSequence({state, commit}, news) {
      return _Promise(updateSequence(news), res => {
        commit('updateProjects', res.data)
      })
    },

    // 删除项目类型
    removeProjects({state, commit}, projects) {
      return _Promise(removeProjects(projects.id), res => {
        commit('removeProjects', projects)
      })
    }
  }
}
